//
//  VideoStartViewController.m
//  Tongcheng
//
//  Created by 邢广范 on 2017/4/3.
//  Copyright © 2017年 Tongcheng. All rights reserved.
//

#import "VideoStartViewController.h"
#import "SRVideoPlayer.h"
#import "VideoStartOperator.h"
#import "VideoStartModel.h"
#import "VideoStartDataModel.h"
#import "VideoStartVideoModel.h"
#import "VideoStartViewerModel.h"
#import "VideoStartViewerListModel.h"
#import "VideoStartTableViewCell.h"
#import "VideoListViewController.h"
#import "UIImageView+AFNetworking.h"
#import "MJRefresh.h"
#import "SendFlower.h"
#import "MineBuyYBViewController.h"
#import "SendFlowerOperator.h"
#import "SendFlowerModel.h"
#import "SendFlowerDataModel.h"

@interface VideoStartViewController ()<UITableViewDelegate,UITableViewDataSource,SendFlowerDelegate>

@property (nonatomic, strong) SRVideoPlayer *videoPlayer;

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, strong) VideoStartVideoModel *dataModel;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *talkView;
@property (weak, nonatomic) IBOutlet UIView *videoView;
@property (weak, nonatomic) IBOutlet UIImageView *avatarImageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *cityLabel;
@property (weak, nonatomic) IBOutlet UILabel *playCountLabel;
@property (weak, nonatomic) IBOutlet UIView *giftView;
@property (nonatomic, strong)SendFlower *flower;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) MJRefreshAutoNormalFooter *footer;

@property (nonatomic, assign) BOOL isPlayVideo;

@end

@implementation VideoStartViewController

static NSString *roseCellIdentifier = @"VideoStartTableViewCell";

- (MJRefreshAutoNormalFooter *)footer
{
    if (_footer == nil) {
        _footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(downloadMore)];
        
    }
    return _footer;
}

- (void)setDataArray:(NSMutableArray *)dataArray
{
    _dataArray = dataArray;
    [self.tableView reloadData];
}

-(NSInteger)page
{
    if (!_page) {
        _page = 1;
    }
    return _page;
}

- (void)setupNavigation
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(clickBack)];
}

- (void)setupView
{
    UIView *playerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 250)];
    [self.view addSubview:playerView];
    
    _videoPlayer = [SRVideoPlayer playerWithVideoURL:[NSURL URLWithString:self.dataModel.file] playerView:playerView playerSuperView:playerView.superview];
    _videoPlayer.videoName = @"Here Is The Video Name";
    _videoPlayer.playerEndAction = SRVideoPlayerEndActionStop;
    [_videoPlayer play];
    
    
    self.giftView.layer.cornerRadius = 5;
    self.giftView.layer.masksToBounds = YES;
    UITapGestureRecognizer *giftTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickGiftView)];
    [self.giftView addGestureRecognizer:giftTap];

    [self.view bringSubviewToFront: self.giftView];
    
    if (self.isShowBottomView) {
        self.talkView.hidden = NO;
        self.videoView.hidden = NO;
    }else{
        self.talkView.hidden = YES;
        self.videoView.hidden = YES;
    }
    
    self.navigationItem.title = self.dataModel.title;
    
    self.avatarImageView.layer.cornerRadius = 5;
    self.avatarImageView.layer.masksToBounds = YES;
    [self.avatarImageView setImageWithURL:[NSURL URLWithString:self.dataModel.avatar] placeholderImage:nil];
    self.nameLabel.text = self.dataModel.nicename;
    self.cityLabel.text = self.dataModel.provinceid;
    self.playCountLabel.text = [NSString stringWithFormat:@"%@次播放", self
                                .dataModel.views];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UITapGestureRecognizer *talkTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickTalkView)];
    [self.talkView addGestureRecognizer:talkTap];
    
    UITapGestureRecognizer *videoTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickVideoView)];
    [self.videoView addGestureRecognizer:videoTap];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        self.isPlayVideo = YES;
        [self download];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavigation];
    [self download];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoStartTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:roseCellIdentifier];
    if (!cell) {
        cell = [[UINib nibWithNibName:@"VideoStartTableViewCell" bundle:nil] instantiateWithOwner:self options:nil].lastObject;
    }
    VideoStartViewerListModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (void)clickTalkView
{
    NSLog(@"去聊天");
}

- (void)clickGiftView
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"token"] = self.config.token;
    dic[@"user_id"] = self.config.userId;
    dic[@"Num"] = @"1";
    dic[@"Video_id"] = self.videoId;
    dic[@"to_uid"] = self.dataModel._id;
    SendFlowerOperator *operator = [[SendFlowerOperator alloc] initWithParams:dic];
    [self.networkingManager asyncTaskOnVC:self operator:operator successBlock:^(BaseModel *baseModel) {
        [self showToastMessage:baseModel.msg];
        if (![baseModel.code isEqualToString:@"1"]) {
            _flower = [SendFlower gainMineHeaderView];
            _flower.delegate = self;
            [self.view addSubview:_flower];
        }
    } failBlock:^(BaseModel *baseModel) {
        
    }];
}

- (void)GoCharege {
    MineBuyYBViewController *buy = [[MineBuyYBViewController alloc] init];
    [_flower removeFromSuperview];
    [self.navigationController pushViewController:buy animated:YES];
}

- (void)clickVideoView
{
    VideoListViewController *listVc = [[VideoListViewController alloc] init];
    listVc.userId = self.dataModel.user_id;
    [self.navigationController pushViewController:listVc animated:YES];
}

- (void)clickBack
{
    [_videoPlayer destroyPlayer];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)download
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"token"] = self.config.token;
    dic[@"user_id"] = self.config.userId;
    dic[@"id"] = self.videoId;
    dic[@"Page"] = [NSString stringWithFormat:@"%ld", self.page];
    dic[@"Row"] = @"30";
    VideoStartOperator *operator = [[VideoStartOperator alloc] initWithParams:dic];
    [self.networkingManager asyncTaskOnVC:self operator:operator successBlock:^(BaseModel *baseModel) {
        [self.tableView.mj_header endRefreshing];
        if ([baseModel.code isEqualToString:@"1"]) {
            self.page ++;
            self.dataArray = [NSMutableArray arrayWithArray:operator.data.data.viewers.list];
            self.dataModel = operator.data.data.video;
            if (self.dataArray.count < 30) {
                self.tableView.mj_footer = nil;
            }else{
                self.tableView.mj_footer = self.footer;
            }
            if (!self.isPlayVideo) {
                [self setupView];
            }
        }
    } failBlock:^(BaseModel *baseModel) {
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)downloadMore
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"token"] = self.config.token;
    dic[@"user_id"] = self.config.userId;
    dic[@"id"] = self.videoId;
    dic[@"Page"] = [NSString stringWithFormat:@"%ld", self.page];
    dic[@"Row"] = @"30";
    VideoStartOperator *operator = [[VideoStartOperator alloc] initWithParams:dic];
    [self.networkingManager asyncTaskOnVC:self operator:operator successBlock:^(BaseModel *baseModel) {
        if ([baseModel.code isEqualToString:@"1"]) {
            self.page ++;
            NSArray *array = operator.data.data.viewers.list;
            if (array.count < 30) {
                self.tableView.mj_footer = nil;
            }else{
                self.tableView.mj_footer = self.footer;
            }
            NSMutableArray *MutableArray = [NSMutableArray arrayWithArray:self.dataArray];
            [MutableArray addObjectsFromArray:array];
            self.dataArray = MutableArray;
            self.dataModel = operator.data.data.video;
            if (!self.isPlayVideo) {
                [self setupView];
            }
        }
    } failBlock:^(BaseModel *baseModel) {
        
    }];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_videoPlayer pause];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
